<template>
  <div class="app-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>学生信息管理</span>
          <el-button
            type="primary"
            icon="el-icon-plus"
            @click="handleAdd"
            v-hasPermi="['student:info:add']"
            class="ml-4"
          >
            新增学生
          </el-button>
        </div>
      </template>

      <div class="filter-container">
        <el-input
          v-model="queryParams.studentName"
          placeholder="请输入学生姓名"
          clearable
          size="small"
          class="mb-2 mr-2"
          style="width: 240px"
        />
        <el-select
          v-model="queryParams.gender"
          placeholder="请选择性别"
          clearable
          size="small"
          class="mb-2 mr-2"
          style="width: 120px"
        >
          <el-option label="男" value="0" />
          <el-option label="女" value="1" />
          <el-option label="未知" value="2" />
        </el-select>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="small"
          @click="handleQuery"
          class="mb-2"
        >
          搜索
        </el-button>
        <el-button
          icon="el-icon-refresh"
          size="small"
          @click="resetQuery"
          class="mb-2"
        >
          重置
        </el-button>
      </div>

      <el-table
        v-loading="loading"
        :data="studentList"
        @selection-change="handleSelectionChange"
        border
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="学生ID" prop="studentId" align="center" width="80" />
        <el-table-column label="学生姓名" prop="studentName" align="center" />
        <el-table-column label="头像" align="center" width="100">
          <template slot-scope="scope">
            <el-image
              :src="scope.row.avatar || '/avatar/default.jpg'"
              style="width: 60px; height: 60px; border-radius: 50%"
              fit="cover"
              @click="showAvatar(scope.row.avatar)"
            />
          </template>
        </el-table-column>
        <el-table-column label="个人介绍" prop="introduction" align="center" width="300" show-overflow-tooltip />
        <el-table-column label="学生性别" align="center" prop="gender">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.gender === '0'" type="success">男</el-tag>
            <el-tag v-else-if="scope.row.gender === '1'" type="info">女</el-tag>
            <el-tag v-else type="danger">未知</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" prop="status">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.status === '0'" type="success">正常</el-tag>
            <el-tag v-else type="danger">停用</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" prop="createTime" width="180">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.createTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="200" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="primary"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['student:info:edit']"
            >
              修改
            </el-button>
            <el-button
              size="mini"
              type="danger"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['student:info:remove']"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>

    <!-- 添加或修改学生信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="学生姓名" prop="studentName">
          <el-input v-model="form.studentName" placeholder="请输入学生姓名" />
        </el-form-item>
        <el-form-item label="头像地址" prop="avatar">
          <div class="avatar-uploader">
            <el-upload
              class="avatar-uploader"
              action="/common/upload"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
            >
              <img v-if="form.avatar" :src="form.avatar" class="avatar" />
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
            <div class="avatar-tips">请上传大小不超过5MB格式为png/jpg/jpeg的文件</div>
          </div>
        </el-form-item>
        <el-form-item label="个人介绍" prop="introduction">
          <el-input
            v-model="form.introduction"
            type="textarea"
            placeholder="请输入个人介绍"
            rows="6"
          />
        </el-form-item>
        <el-form-item label="学生性别" prop="gender">
          <el-select v-model="form.gender" placeholder="请选择性别">
            <el-option label="男" value="0" />
            <el-option label="女" value="1" />
            <el-option label="未知" value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio label="0">正常</el-radio>
            <el-radio label="1">停用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 头像预览 -->
    <el-dialog :visible.sync="avatarDialogVisible" width="500px" title="头像预览">
      <el-image :src="avatarUrl" fit="contain" style="width: 100%; height: 400px" />
    </el-dialog>
  </div>
</template>

<script>
import { listInfo, getInfo, delInfo, addInfo, updateInfo } from "@/api/system/info";
import { parseTime, resetForm, msgSuccess } from "@/utils/ruoyi";
import { ElMessage } from "element-ui";

export default {
  name: "StudentInfo",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 学生信息表格数据
      studentList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        studentName: null,
        gender: null,
        status: null,
      },
      // 表单参数
      form: {
        studentId: null,
        studentName: null,
        avatar: null,
        introduction: null,
        gender: "0",
        status: "0",
        delFlag: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      },
      // 表单校验
      rules: {
        studentName: [
          { required: true, message: "学生姓名不能为空", trigger: "blur" }
        ],
        gender: [
          { required: true, message: "性别不能为空", trigger: "change" }
        ],
        status: [
          { required: true, message: "状态不能为空", trigger: "change" }
        ]
      },

      // 头像预览相关
      avatarDialogVisible: false,
      avatarUrl: ''
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询学生信息列表 */
    getList() {
      this.loading = true;
      listInfo(this.queryParams).then(response => {
        this.studentList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        studentId: null,
        studentName: null,
        avatar: null,
        introduction: null,
        gender: "0",
        status: "0",
        delFlag: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      };
      this.resetForm("form");
    },
    // 搜索按钮
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    // 重置按钮
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.studentId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    // 新增按钮
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "新增学生";
    },
    // 修改按钮
    handleUpdate(row) {
      this.reset();
      const studentId = row.studentId;
      getInfo(studentId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改学生";
      });
    },
    // 删除按钮
    handleDelete(row) {
      const studentIds = row.studentId || this.ids;
      this.$confirm(
        "是否确认删除学生编号为" + studentIds + "的数据项?",
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      )
        .then(function() {
          return delInfo(studentIds);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    // 提交表单
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.studentId != null) {
            updateInfo(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              }
            });
          } else {
            addInfo(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              }
            });
          }
        }
      });
    },
    // 头像上传成功
    handleAvatarSuccess(res, file) {
      if (res.code === 200) {
        this.form.avatar = res.url;
        ElMessage.success("上传成功");
      } else {
        ElMessage.error(res.msg || "上传失败");
      }
    },
    // 头像上传前校验
    beforeAvatarUpload(file) {
      const isPNG = file.type === 'image/png';
      const isJPG = file.type === 'image/jpeg';
      const isJPEG = file.type === 'image/jpeg';
      const isLt5M = file.size / 1024 / 1024 < 5;

      if (!isPNG && !isJPG && !isJPEG) {
        ElMessage.error('上传头像图片只能是 PNG、JPG、JPEG 格式!');
      }
      if (!isLt5M) {
        ElMessage.error('上传头像图片大小不能超过 5MB!');
      }
      return (isPNG || isJPG || isJPEG) && isLt5M;
    },
    // 显示头像
    showAvatar(avatar) {
      if (avatar) {
        this.avatarUrl = avatar;
        this.avatarDialogVisible = true;
      }
    },

  }
};
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.filter-container {
  padding: 20px 0;
  background-color: #f5f7fa;
  margin: -20px -20px 20px;
  padding: 20px;
  border-bottom: 1px solid #ebeef5;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 150px;
  height: 150px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 32px;
  color: #8c939d;
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.avatar {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.avatar-tips {
  margin-top: 10px;
  font-size: 12px;
  color: #f56c6c;
}

/* 表格样式优化 */
/deep/ .el-table {
  border: 1px solid #ebeef5;
}

/deep/ .el-table__header-wrapper {
  border-bottom: 2px solid #409eff;
}

/deep/ .el-table__header th {
  background-color: #ecf5ff;
  color: #269abc;
  font-weight: bold;
}

/* 标签样式 */
/deep/ .el-tag {
  padding: 4px 12px;
  border-radius: 12px;
}

/deep/ .el-tag--success {
  background-color: #f0f9eb;
  border-color: #e1f3d8;
  color: #67c23a;
}

/deep/ .el-tag--info {
  background-color: #f4f4f5;
  border-color: #ebeef5;
  color: #909399;
}

/deep/ .el-tag--danger {
  background-color: #fef0f0;
  border-color: #fde2e2;
  color: #f56c6c;
}

/* 表单样式优化 */
/deep/ .el-form-item {
  margin-bottom: 24px;
}

/deep/ .el-textarea__inner {
  border-radius: 4px;
  min-height: 120px;
}

/* 按钮样式优化 */
/deep/ .el-button--primary {
  background-color: #409eff;
  border-color: #409eff;
}

/deep/ .el-button--danger {
  background-color: #f56c6c;
  border-color: #f56c6c;
}
</style>